package com.upsuns.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 *@Description:<p>服务端，基于Netty的NIO模型</p>
 *@author 王旭
 *@time 2016年3月18日 下午10:18:03
 */
public class TimeServer {
	
	private int port;
	
	public TimeServer(int port) {
		this.port = port;
	}
	
	public void doServer() {
		EventLoopGroup parentGroup = new NioEventLoopGroup();
		EventLoopGroup childGroup = new NioEventLoopGroup();
		
		ServerBootstrap boot = new ServerBootstrap();
		
		boot.group(parentGroup, childGroup)
			.channel(NioServerSocketChannel.class)
			.option(ChannelOption.SO_BACKLOG, 1024)
			.childHandler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new TimeServerHandler());
				}
				
			});
		
		ChannelFuture cf;
		try {
			cf = boot.bind(port).sync(); //等待绑定监听端口成功
			cf.channel().closeFuture().sync(); //等待监听端口关闭，防止提前退出
		} catch (InterruptedException e) {
			parentGroup.shutdownGracefully();
			childGroup.shutdownGracefully();
		}
	}

}
